package logic

import (
	"whale/internal/app/admin/consts/req"
	"whale/internal/app/admin/consts/res"
	"whale/internal/app/admin/errors"
	"whale/internal/app/admin/model"
	"whale/internal/repository"
	"whale/pkg/utils"
)

// logic *MenuLogic IMenuLogic
type IMenuLogic interface {
	// 菜单列表
	GetList(data req.PagingReq) (interface{}, error)
	// 菜单详情
	GetInfo(id int) (interface{}, error)
	// 创建菜单
	Create(data req.MenuCreateReq) error
	// 更新菜单
	Update(data req.MenuUpdateReq) error
	// 更新状态
	Set(data req.SetDataReq) error
	// 删除广告
	Deleted(id int) error
}

// 更新状态
func (logic *MenuLogic) Set(data req.SetDataReq) error {
	if ok := utils.ContainsKeyInSlice(data.Value, []string{"status", "sort"}); ok {
		return errors.ContainsKeyError()
	}

	if err := logic.Repository.Table(&model.Menu{}).Where("id = ?", data.Id).Update(data.Value); err != nil {
		return errors.DBStoreError()
	}
	return nil
}

// 广告列表
func (logic *MenuLogic) GetList(data req.PagingReq) (interface{}, error) {
	var list []res.MenuListRes
	if err := logic.Repository.Table(&model.Menu{}).Paging(data.Page, data.PageSize).OrderBy("sort desc").GetList(&list); err != nil {
		return nil, errors.DBReadError()
	}
	return list, nil
}

// 广告详情
func (logic *MenuLogic) GetInfo(id int) (interface{}, error) {
	var info res.MenuInfoRes

	if _, err := logic.Repository.Table(&model.Menu{}).Where("id = ?", id).Get(&info); err != nil {
		return nil, errors.DBReadError()
	}
	return info, nil
}

// 创建广告
func (logic *MenuLogic) Create(data req.MenuCreateReq) error {
	var menuData model.Menu

	if err := utils.StructCopy(&menuData, &data); err != nil {
		return errors.StructCopyError()
	}

	if err := logic.Repository.Table(&model.Menu{}).Insert(&menuData); err != nil {
		return errors.DBStoreError()
	}
	return nil
}

// 更新广告
func (logic *MenuLogic) Update(data req.MenuUpdateReq) error {
	var menuData model.Menu

	if err := utils.StructCopy(&menuData, &data); err != nil {
		return errors.StructCopyError()
	}

	if err := logic.Repository.Table(&model.Menu{}).Where("id = ?", data.Id).Update(&menuData); err != nil {
		return errors.DBStoreError()
	}
	return nil
}

// 删除广告
func (logic *MenuLogic) Deleted(id int) error {
	if err := logic.Repository.Table(&model.Menu{}).Where("id = ?", id).Deleted(); err != nil {
		return errors.DBStoreError()
	}
	return nil
}

type MenuLogic struct {
	Repository repository.IRepository `bean:"Repository"`
}
